#include"Thread.hpp"
#include"Mutex.hpp"
int g_val =100;
int ticket =10000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
std::string changeId(const pthread_t &thread_id)
{
    char tid[128];
    snprintf(tid, sizeof(tid), "0x%x", thread_id);
    return tid;
}
void *start_routine(void *args)
{
    std::string threadname = static_cast<const char *>(args);
    // pthread_detach(pthread_self()); //设置自己为分离状态

    int cnt = 5;
    while (true)
    {
        std::cout << threadname << " running ... : " << changeId(pthread_self()) <<" g_val: "<< g_val << " &g_val: " << &g_val << std::endl;
        sleep(1);
        g_val++;
    }

    return nullptr;
}


void* getTicket(void* arg)
{
    std::string username = static_cast<const char*>(arg);
    
    while(true)
    {
        // pthread_mutex_lock(&mutex);
        LockGuard lockguard(&lock);
        if(ticket>0)
        {
            usleep(1000);
            // 值得抢票
            std::cout<<username<<"正在抢票："<<ticket<<std::endl;
            ticket--;
            // pthread_mutex_unlock(&mutex);
        }else{
            // pthread_mutex_unlock(&mutex);
            break;
        }
    }
    return nullptr;
}
int main()
{

    // #define NUM 4
    //     pthread_mutex_t lock;
    //     pthread_mutex_init(&lock, nullptr);
    //     std::vector<pthread_t> tids(NUM);
    //     for(int i = 0; i < NUM; i++)
    //     {
    //         char buffer[64];
    //         snprintf(buffer, sizeof(buffer), "thread %d", i+1);
    //         ThreadData *td = new ThreadData(buffer, &lock);
    //         pthread_create(&tids[i], nullptr, getTicket, td);
    //     }

    //     for(const auto &tid: tids)
    //     {
    //         pthread_join(tid, nullptr);
    //     }




    pthread_t t1, t2, t3, t4;
    pthread_create(&t1, nullptr, getTicket, (void *)"thread 1");
    pthread_create(&t2, nullptr, getTicket, (void *)"thread 2");
    pthread_create(&t3, nullptr, getTicket, (void *)"thread 3");
    pthread_create(&t4, nullptr, getTicket, (void *)"thread 4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);



    
    return 0;
}